<?php

require_once(dirname(__FILE__).'/template-functions.php');

function pressless_action_match()
{
  global $pressless_action_files;

  $path_info_parts = explode('/', trim($_SERVER['PATH_INFO'], '/'));
  while ( !empty($path_info_parts) ) {
    $possible_action = implode('-', $path_info_parts);

    if ( isset($pressless_action_files[$possible_action]) ) {
      return $possible_action;
    }

    array_pop($path_info_parts);
  }

  /*
  if ($SERVER['PATH_INFO'] == '/') {
    header("Location: /pressless/welcome");
  }
 */

  return 'pressless-no-such-action';
}

function pressless_include_path()
{
  global $pressless_addons_initialized;

  $dirs[] = PRESSLESS_CUSTOM_DIR . '/libs';

  foreach ($pressless_addons_initialized as $addon)
    $dirs[] = PRESSLESS_ADDONS_DIR . '/' . $addon;

  $dirs[] = PRESSLESS_PRODUCT_DIR . '/libs';

  return implode(':', $dirs);
}

function pressless_error_handler($error_no, $error_message, $error_file_name, $error_line_num, $error_vars)
{
  static $error_types = array (
    E_WARNING            => 'Warning',
    E_NOTICE             => 'Notice',
    E_USER_ERROR         => 'User Error',
    E_USER_WARNING       => 'User Warning',
    E_USER_NOTICE        => 'User Notice',
    E_STRICT             => 'Runtime Notice',
    E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
  );

  $error_file_url = '/pressless/source' . str_replace(realpath(PRESSLESS_ROOT_DIR), '', $error_file_name);

  $vars = array(
    'error_no' => $error_no,
    'error_message' => $error_message,
    'error_file_name' => $error_file_name,
    'error_file_url' => $error_file_url,
    'error_line_num' => $error_line_num,
    'error_vars' => $error_vars,
    'error_type' => $error_types[$error_no],
    'backtrace' => debug_backtrace()
  );

  echo apply_template(PRESSLESS_PRODUCT_DIR.'/error-handler-template.php', &$vars);

  if ($error_type & E_USER_ERROR)
    exit(1);
}

function pressless_exception_handler($exception)
{
  restore_error_handler(); // Don't want any conflicts

  $error_file_url = '/pressless/source' . str_replace(realpath(PRESSLESS_ROOT_DIR), '', $exception->getFile());

  $vars = array(
    'error_no'        => $exception->getCode(),
    'error_message'   => $exception->getMessage(),
    'error_file_name' => $exception->getFile(),
    'error_file_url'  => $error_file_url,
    'error_line_num'  => $exception->getLine(),
//    'error_vars'      => $error_vars,
    'error_type'      => 'Uncaught exception (' . $exception->getCode() . ')',
    'backtrace'       => $exception->getTrace()
  );

  echo apply_template(PRESSLESS_PRODUCT_DIR.'/error-handler-template.php', &$vars);
  exit(1);
}

?>
